<template>
  <div class="NewCard">
    <!-- 图片上传 -->
    <div class="uploadImg" v-show="id == 1">
      <input 
          type="file" 
          ref="fileInput"
          accept="image/*"
          @change="handleFileSelect"
          class="hidden"
        >
      <!-- 上传按钮 -->
      <div class="uploadBtn" @click="triggerFileInput" v-if="store.previewUrl == ''">
        <span class="iconfont icon-tianjia"></span>
      </div>
      <div class="imgView" v-else>
        <div class="edit" @click="triggerFileInput">
          <span class="iconfont icon-tianjia" ></span>
        </div>
        <img class="imgInfo" :src="store.previewUrl" alt="">
      </div>
    </div>

    <!-- 颜色选择器 -->
    <div class="colors">
      <p
        class="color-li"
        v-for="(item, index) in bgColorfill"
        :key="item"
        :style="{ background: item }"
        :class="{ active: activeIndex == index }"
        @click="toggleIndex(index)"
      ></p>
    </div>

    <!-- 输入框 -->
    <div class="card-main" :style="{ background: bgC }">
      <textarea
        name=""
        v-model="message"
        class="message"
        maxlength="96"
        placeholder="请输入..."
      ></textarea>
      <input class="author" type="text" v-model="author" placeholder="签名" />
    </div>

    <!-- 标签 -->
    <div class="labels">
      <p class="title">选择标签</p>
      <div class="labelList">
        <p
          class="label-item"
          :class="{ active: labelIndex == -1 }"
          @click="toggleLabelIndex(-1)"
        >
          全部
        </p>
        <p
          v-for="(item, index) in label[tag]"
          :class="{ active: labelIndex == index }"
          class="label-item"
          @click="toggleLabelIndex(index)"
        >
          {{ item }}
        </p>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="footbar">
      <YkButton size="max" class="cancel" @click="close" type="secondary"
        >取消</YkButton
      >
      <YkButton size="big" class="submit" @click="submit">确定</YkButton>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, reactive, inject } from 'vue'
import { useNewCardStore } from "@/store/newCard.js"
import { useRoute } from 'vue-router'
import { bgColor, bgColorfill, label } from '@/utils/data'
import { getIpInfo, addWall } from '@/api/walls'
import YkButton from '@/components/YkButton.vue'

const route = useRoute()

const store = useNewCardStore()

const $message = inject('$message')

const props = defineProps({
  tag: {
    type: [Number, String],
    defualt: 0,
  },
})

const emits = defineEmits(['close', 'reload'])

// 防抖定时器
let timer = null

// 提交数据
const form = reactive({
  type: 0,
  message: '',
  name: '',
  userId: '',
  moment: new Date(),
  label: 0,
  color: 0,
  imgUrl: 0,
})

// 获取路由id
const id = computed(() => {
  return Number(route.query.id)
})

//  选中的色块下标
const activeIndex = ref(0)

// 标签下标
const labelIndex = ref(-1)
// 背景色监听
const bgC = computed(() => {
  return bgColor[activeIndex.value]
})

// 文件选择器
const fileInput = ref(null)
// 预览图片
const previewUrl = ref('')
// 留言内容
const message = ref('')
// 作者名称
const author = ref('')

// 文件选择
function handleFileSelect(e) {
  const file = e.target.files[0];
  validateAndPreview(file);
}
// 触发文件选择
function triggerFileInput () {
  fileInput.value.click()
}

// 验证文件并预览
const validateAndPreview = (file) => {
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    $message({type: 'error', message: '请选择有效的图片文件'})
    return;
  }
  // 验证文件大小
  if (file.size > 2 * 1024 * 1024) {
    $message({type: 'error', message: '文件大小不能超过2MB'})
    return;
  }
  // 显示预览
  const reader = new FileReader();
  reader.onload = (e) => {
    // previewUrl.value = e.target.result;
    store.setprevImg(e.target.result, fileInput)
  };
  reader.readAsDataURL(file);
};

// 切换选中的下标
function toggleIndex(val) {
  activeIndex.value = val
}

// 切换标签下标
function toggleLabelIndex(val) {
  labelIndex.value = val
}

// 关闭弹窗
function close() {
  store.clearUrl()
  fileInput.value.value = '';
  emits('close')
}

// 提交数据
async function submit() {
  if (message.value.trim() == '') {
    $message({type: 'error', message: "请输入留言"})
    return
  }
  if (author.value.trim() == '') {
    author.value = '匿名'
  }

  if (timer != null) {
    clearTimeout(timer)
  }
  timer = setTimeout(async () => {
    const ipInfo = await getIpInfo()
    form.userId = ipInfo.ip
    form.moment = new Date()
    form.type = id.value
    form.imgUrl = activeIndex.value
    form.label = labelIndex.value
    form.message = message.value
    form.name = author.value
    const res = await addWall(form)
    console.log(res)
    if (res.code == 200) {
      // 提示信息
      $message({ type: 'success', message: '留言成功' })
      // 刷新留言
      emits('reload')
      // 清空表单
      message.value = ''
      author.value = ''
      // 关闭弹窗
      close()
      // 清空定时器
      clearTimeout(timer)
    }
  }, 300);
}

</script>

<style lang="less" scoped>
.NewCard {
  box-sizing: border-box;
  width: 100%;
  padding: 0 @padding-20;
  position: relative;

  // 上传图片
  .uploadImg {
    padding-bottom: @padding-20;
    .hidden {
      display: none;
    }
    // 上传按钮
    .uploadBtn {
      width: 45px;
      height: 45px;
      border-radius: 50%;
      border: 2px solid @gray-2;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
    // 预览图片
    .imgView {
      width: 100%;
      position: relative;
      .edit {
        position: absolute;
        left: 10px;
        top: 10px;
        z-index: 10;
        cursor: pointer;
        width: 25px;
        height: 25px;
        border-radius: 50%;
        border: 2px solid @gray-1;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .imgInfo {
        width: 100%;
      }
    }
  }

  // 色块
  .colors {
    display: flex;
    .color-li {
      width: 25px;
      height: 25px;
      margin-right: @padding-8;
      cursor: pointer;
    }
    .color-li.active {
      border: 1px solid @gray-2;
    }
  }
  // 内容输入区域
  .card-main {
    box-sizing: border-box;
    width: 100%;
    height: 240px;
    margin-top: 10px;
    padding: 12px;
    .message {
      width: 100%;
      background: none;
      border: none;
      resize: none;
      height: 170px;
      padding-left: @padding-8;
      font-family: '宋体';
    }
    .author {
      height: 36px;
      width: 100%;
      box-sizing: border-box;
      background: none;
      border: none;
      border: 1px solid #fff;
      padding: @padding-8;
      font-family: '宋体';
    }
  }

  // 标签
  .labels {
    .title {
      color: @gray-1;
      font-weight: 600;
      margin-top: 20px;
      margin-bottom: 10px;
    }

    .labelList {
      display: flex;
      flex-wrap: wrap;
      .label-item {
        padding: 2px 8px;
        margin-bottom: @padding-8;
        border-radius: 20px;
        cursor: pointer;
        transition: 0.3s;
        &.active {
          background: #e8e8e8;
          font-weight: 600;
          color: @gray-1;
        }
      }
    }
  }

  .footbar {
    position: fixed;
    padding: @padding-20 0;
    width: 100%;
    display: flex;
    bottom: 40px;
    YkButton {
      cursor: pointer;
    }
    .submit {
      margin-left: @padding-20;
    }
  }
}
</style>
